var app = getApp();
var util = require('../../../utils/util.js');
var one_id = 0;
var two_id = 0;
var status;   //上架-下架的输入值 0代表上架 1代表下架
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isxiajia: false, // 下架框
    isshangjia: false, // 上架框
    isdel: false,   // 删除框
    choose: 0,     //一级分类选择索引
    leftChoose:0,    //二级分类选择索引
    isguige:[],   //规格显隐
    isopacity:0,
    page:1,  //当前页码
    allpage:1,
    count:0, //选择数量
    isopera:false, //控制'操作'
    value:[0,0],  //底部弹窗初始值
    load:"加载中...",
    oldlist:[],
    is_checked: {},//单选
    isChooseAll: false, //全选
    stopstart: false,
    sole:0,  //检测上拉是否触底  0未触底 1触底
    isshowmore:1,  //二级更多,1展开平铺 2展开绝对定位 3收起
    loading:1
  },
  noneEnoughPeople:function(){
    return;
  },
  close_opera:function(){
    this.setData({
      isopera:false
    });
  },
  // 去搜索商品页面
  tosearshop:function(){
    wx.navigateTo({
      url: 'searshop/searshop'
    })
  },
  // 二级显示
  showmore:function(){
    var isshowmore=this.data.isshowmore;
    this.setData({
      isshowmore:isshowmore==3?2:3,
      isopacity:1,
      opac:1
    });
  },
  // 点击 “操作” 
  operack:function(){
    this.setData({
      isopera:!this.data.isopera
    })
  },
  // 显示规格
  showspecs:function(e){
    var that = this;
    var index = e.currentTarget.id;
    that.setData({
      isguige:[]
    });
    app.AppHttp('api/Supplier/getSpecs', {
      openid: app.globalData.openid,
      good_id: that.data.rightDatas[index].id
    }, function (res) {
      console.log(JSON.stringify(res.data));  
      that.setData({
        specs_list: res.data.specs_list,
        ["isguige[" + index + "]"]: true
      })  
    });
  },
  // 隐藏规格
  hidespecs:function(e){
    var index = e.currentTarget.id
    this.setData({
      ["isguige[" + index + "]"]: false
    })
  },
  // 表单选择
  checkboxChange:function(e){
    var is_checked = {};
    for (var i = 0; i < e.detail.value.length; i++) {  
      is_checked[e.detail.value[i]] = true;
    };
    if (e.detail.value.length == this.data.rightDatas.length) {
      this.setData({
        isChooseAll: true,
        is_checkall: true,
        is_checked: is_checked,
        count: e.detail.value.length
      })
    } else {
      this.setData({
        isChooseAll: false,
        is_checkall: false,
        is_checked: is_checked,
        count: e.detail.value.length
      })
    }
  },
  // 全选
  chooseAll: function (e) {
    var is_checked={};
    if (!this.data.isChooseAll){
      for (var i = 0; i < this.data.rightDatas.length; i++) {
        is_checked[this.data.rightDatas[i].id] = true;     
      };
    };
    this.setData({
      isChooseAll: !this.data.isChooseAll,
      is_checkall: !this.data.isChooseAll,
      is_checked: is_checked,
      count: !this.data.isChooseAll == true ? this.data.rightDatas.length : 0
    })
  },
  // 阻止checkboxChange表单冒泡
  checkboxMerge:function(){
    return;
  },
  // 表单提交
  formSubmit:function(e){
    if (e.detail.target.dataset.status=='move'){
      this.setData({
        ids: e.detail.value.shoptype
      })
      this.movechooseTap();
    }else if (e.detail.target.dataset.status == 'xiajia'){
      this.setData({
        ids: e.detail.value.shoptype
      })
      this.xiajia();
    } else if (e.detail.target.dataset.status == 'shangjia'){
      this.setData({
        ids: e.detail.value.shoptype
      })
      this.shangjia();
    }else if (e.detail.target.dataset.status == 'del') {
      this.setData({
        ids: e.detail.value.shoptype
      })
      this.del();
    }    
  },
  // 点击移动
  movechooseTap: function () {
    var types = this.data.types;
    var leftTypes = this.data.leftTypes;
    var typesmove = types;
    var val=this.data.value;
    util.showBuyModal(this);
    this.setData({
      showModalStatus:true,
      typesmove: typesmove,
      leftTypesmove: leftTypes,
      one_class: typesmove[val[0]].private_one_class,
      two_class: leftTypes[val[1]].private_one_class,
      nomove_class:[typesmove[val[0]].private_one_class,leftTypes[val[1]].private_one_class]
    })
    console.log(this.data.one_class);
    console.log(this.data.two_class);
  },
  // 底部弹窗选择改变
  bindChange: function (e) {
    var that = this;
    var val = e.detail.value;
    var typesmove = that.data.typesmove;
    app.AppHttp('api/Supplier/CateList',{
      openid: app.globalData.openid,
      id: app.globalData.loginInfo.id,
      one_id: typesmove[val[0]].private_one_class,
      page:1,
      limit:20,
      e_type:'client'
    }, function (res) {
      console.log(JSON.stringify(res.data));
      console.log(res.data.two_class_list.length);
      if (val[1] > res.data.two_class_list.length-1) {
        val[1] = res.data.two_class_list.length-1
      }
      if (res.data.two_class_list.length==0){
        that.setData({
          leftTypesmove: [''],
          one_class: res.data.one_class_list[val[0]].private_one_class,
          two_class:-1
        })
        return;
      }
      that.setData({
        leftTypesmove: res.data.two_class_list,
        one_class: res.data.one_class_list[val[0]].private_one_class,
        two_class: res.data.two_class_list[val[1]].private_one_class
      });
    })
  
  },
  // 点击确定移动
  queding: function (e) {
    var that = this;
    console.log(that.data.ids);
    console.log(that.data.one_class);
    console.log(that.data.two_class);
    if (that.data.two_class==-1){
      wx.showToast({
        title: '没有二级分类'
      })
      return;
    }
    app.AppHttp('api/Supplier/removeProduct', {
      ids: that.data.ids,
      one_class: that.data.one_class,
      two_class: that.data.two_class
    }, function (res) {
      // console.log(JSON.stringify(res.data))
        wx.showToast({
          title: res.data.msg
        },2000)
      if (res.data.status==1){
        var rightDatas=that.data.rightDatas;
        if(that.data.one_class!=that.data.nomove_class[0] || that.data.two_class!=that.data.nomove_class[1]){  //移动       
          var rightDatas = rightDatas.filter(function (item) {  //数组过滤
            //元素值，元素的索引，原数组。
            return (!that.data.is_checked[item.id]);
          });
        };
        that.setData({
          // page: 1,
          // rightDatas: [],
          rightDatas:rightDatas,
          isopera: false,
          is_checked: {},//单选
          isChooseAll: false, //全选
          is_checkall: false,
          count:0,
          // load: "加载中..."
        })
      }
      console.log(JSON.stringify(res.data));
    })
    util.hideBuyModal(this,"showModalStatus");
    // that.upshoplist();
  },
  // 关闭底部移动弹窗
  movecancel:function(){
    util.hideBuyModal(this,"showModalStatus");
  },
  // 下架弹窗
  xiajia:function(){
    this.setData({
      isxiajia: true
    })
  },
  // 下架弹窗关闭
  xiacancel:function(){
    this.setData({
      isxiajia: false,
      isopera: false
    })
  },
  // 确定下架
  xiaconfirm:function(){
    status=1;
    var that = this;
    var rightDatas=this.data.rightDatas;
    var rightDatas = rightDatas.map(function(item) {
      if(that.data.is_checked[item.id]){
        item.status=0;    
      };
      return (item);     
    });
    this.display();
    this.setData({
      isxiajia: false,
      rightDatas: rightDatas,
      isopera: false,
      count: 0,
      is_checked: {},//单选
      isChooseAll: false, //全选
      is_checkall: false
    })
  },
  // 上架弹窗
  shangjia:function(){
    this.setData({
      isshangjia: true
    })
  },
  // 上架弹窗关闭
  shangcancel: function () {
    this.setData({
      isshangjia: false,
      isopera: false
    })
  },
  // 确定上架
 shangconfirm:function(){
   status = 0;
   var that = this;
   var rightDatas=this.data.rightDatas;
    var rightDatas = rightDatas.map(function(item) {
      if(that.data.is_checked[item.id]){
        item.status=1;    
      };
      return (item);     
    });
   this.display();
   this.setData({
    isshangjia: false,
    isopera: false,
    rightDatas: rightDatas,
    count: 0,
    is_checked: {},//单选
    isChooseAll: false, //全选
    is_checkall: false
   });
 },
//  商品上架-下架共用接口
  display:function(){
    var that = this;
    app.AppHttp('api/Supplier/LowerShelf', {
      ids: that.data.ids,
      status: status
    }, function (res) {
      // console.log(JSON.stringify(res.data))
      if (res.data.status) {
        wx.showToast({
          title: res.data.msg
        })
      }
      console.log(JSON.stringify(res.data));
    })
  },
  // 删除弹窗
  del: function () {
    this.setData({
      isdel: true
    })
  },
  // 关闭删除弹窗
  delcancel: function () {
    this.setData({
      isdel: false,
      isopera: false
    })
  },
  // 确定删除弹窗
  delconfirm: function () {
    var that = this;
    app.AppHttp('api/Supplier/deleteGoods', {
      ids: that.data.ids
    }, function (res) {
      // console.log(JSON.stringify(res.data))
      if (res.data.status) {
        wx.showToast({
          title: res.data.msg
        });
        var rightDatas=that.data.rightDatas;   
        var rightDatas = rightDatas.filter(function (item) {  //数组过滤
          //元素值，元素的索引，原数组。
          return (!that.data.is_checked[item.id]);
        });
        that.setData({
          isdel: false,
          // page:1,
          // rightDatas:[],
          isdel:false,
          rightDatas:rightDatas,
          isopera: false,
          is_checked: {},//单选
          isChooseAll: false, //全选
          is_checkall: false,
          count: 0,
          // load: "加载中..."
        })
      }
    });  
  },
  // 添加新品
  addnew:function(){
    wx.navigateTo({
      url: 'newshopdoor/newshopdoor'
    })
  },
  // 类管理
  classmanage:function(){
    wx.navigateTo({
      url: 'classguanli/classguanli?template_id=' + this.data.template_id
    })
  },
  // 去模板库
  tomobanku:function(){
    wx.navigateTo({
      url: "/pages/shangpin/mobanku/mobanku"
    })
  },
  // 编辑产品
  editchanpin:function(e){
    app.globalData.goodid = e.currentTarget.dataset.goodid;
    app.globalData.is_basic_search = e.currentTarget.dataset.is_basic_search;
    var index=e.currentTarget.dataset.index;
    wx.navigateTo({
      url: 'bianjichanpin/bianjichanpin_x?k_index='+index
    });
  },
  // 一级分类切换选择
  typeClick: function (event) {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    });
    let offsetTop = event.currentTarget.offsetTop;   
    this.setData({
      scrollLeft: offsetTop - (this.data.height-this.data.wpx)/2,
      sole:0,
      isopera:false,
      is_checked: {},//单选
      isChooseAll: false, //全选
      is_checkall:false,
      choose: event.currentTarget.dataset.id,
      value: [event.currentTarget.dataset.id,0],
      leftChoose: 0,
      isshowmore:1,
      isopacity:0,
      opac:0,
      page:1,
      count: 0,
      isguige: [],
      load: "加载中..."
    });
    one_id = this.data.types[this.data.choose].private_one_class;
    two_id = 0;
    this.upshoplist();
  },
  // 二级分类切换选择
  leftClick: function (event) {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    })
    this.setData({
      sole:0,
      is_checked: {},//单选
      isChooseAll: false, //全选
      is_checkall: false,
      leftChoose: event.currentTarget.id,
      isshowmore:this.data.isshowmore==1?1:3,
      isopacity:event.currentTarget.dataset.opac,
      opac:event.currentTarget.dataset.opac,
      value: [this.data.choose, event.currentTarget.id],
      page: 1,
      count: 0,
      isopera:false,
      isguige: [],
      load: "加载中..."
    }); 
    one_id = this.data.types[this.data.choose].private_one_class;
    two_id = this.data.leftTypes[this.data.leftChoose].private_one_class;
    this.upshoplist();
  },
  /**
   * 生命周期函数--监听页面加载
   */ 
  onLoad: function () {
    this._observer = wx.createIntersectionObserver(this,{thresholds:[0,0.2,0.4,0.6,0.7,0.8,1]})
    this._observer
      .relativeTo('.shop_list')
      .observe('.empty_90', (res) => {
        if(this.data.isopacity==0){
          this.setData({
            isshowmore:res.intersectionRatio>0?3:1,
            opac:res.intersectionRatio
          });
        };   
    });
    this.upshoplist();
    var height;
    const query = wx.createSelectorQuery();
      query.select('.gouwu-img-box').boundingClientRect();
      query.exec((res) => {
        console.log(res[0].top);
        height=res[0].top; 
        var wpx =120 / 750 * wx.getSystemInfoSync().windowWidth;
        this.setData({
          wpx:wpx,
          height:height
        })
    });
  },
  upshoplist: function (){
    if(this.data.page==1){
      wx.showLoading({
        title: this.data.load
      });
    };
    var that = this;
    app.AppHttp('api/Supplier/good_manage', {
      openid: app.globalData.openid,
      id: app.globalData.loginInfo.id,
      e_type:'client',
      page:that.data.page,
      limit:10,
      one_id: one_id,
      two_id: two_id
    }, function (res) {
      console.log(JSON.stringify(res.data));
      app.globalData.shop_manage = 0;
      var rightDatas= that.data.rightDatas;
      if(that.data.page==1){
        that.setData({
          loading:0,
          cur_page_index:0,
          rightDatas: res.data.goodList[0],
          types: res.data.one_class_list,
          leftTypes: res.data.two_class_list,
          allpage: res.data.goodList[1],
          t_count: res.data.t_count,
          template_id: res.data.template_id,
          one_id: res.data.one_id,
          two_id: res.data.two_id
        })
      }else{
        that.setData({
          loading:0,
          cur_page_index:rightDatas.length,
          rightDatas: that.data.rightDatas.concat(res.data.goodList[0]),
          types: res.data.one_class_list,
          leftTypes: res.data.two_class_list,
          allpage: res.data.goodList[1],
          t_count: res.data.t_count,
          template_id: res.data.template_id,
          one_id: res.data.one_id,
          two_id: res.data.two_id
        })
      } 
      wx.hideLoading();
    })
  },
  touchStart: function (e) {
    let sx = e.touches[0].pageX;
    let sy = e.touches[0].pageY;
    this.data.touchS = [sx, sy];
    this.setData({
      is_start: true
    });
  },
  touchMove: function (e) {
    let sx = e.touches[0].pageX;
    let sy = e.touches[0].pageY;
    this.data.touchE = [sx, sy];
    this.setData({
      is_move: true
    });
  },
  touchEnd: function (e) {
    if (this.data.is_start == true && this.data.is_move == true) {
      let start = this.data.touchS;
      let end = this.data.touchE;
      var t_sy=end[1] - start[1]; //y轴滑动方向及距离    
      if(t_sy<-150 && this.data.sole==1){
        // this.next_class();
      };
      this.setData({       
        is_start: false,
        is_move: false
      });
    }
  },
  onPageScroll: function (e) {
    var that = this;
    this.setData({
      stopstart: true
    })
    if (this.scrollEndTimer) {
      clearTimeout(this.scrollEndTimer);
      this.scrollEndTimer = null;
    }
    this.scrollEndTimer = setTimeout(function () {
      // console.log('滑动结束');
      that.setData({
        stopstart: false
      });
    }, 500);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady(){
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.shop_manage == 1){
      this.setData({
        isguige:[],
        count: 0,
        isopera:false,
        is_checked: {},//单选
        isChooseAll: false, //全选
        is_checkall: false,
        bottomguige: false,
        load: "加载中...",
        page:1,
        rightDatas: []
      });
      this.upshoplist();
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function(){
    if(this._observer) this._observer.disconnect();
    one_id = 0;
    two_id = 0;
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;
    if (that.data.page <that.data.allpage) {
      that.setData({
        page:that.data.page + 1,
        isChooseAll: false, //全选
        is_checkall: false,
        loading:1,
        load: '加载更多'
      });
      that.upshoplist();
    }else{
      wx.showToast({
        title:'没有了'
      });
      this.setData({
        loading:0,
        sole:1
      });
      
    }
  },
  // 上拉加载下一个分类
  next_class:function(){
    if(parseInt(this.data.leftChoose)+1<this.data.leftTypes.length){  //最后一页二级菜单自动切换下一个
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 0
      });
      var leftChoose=parseInt(this.data.leftChoose)+1;
      this.setData({
        sole:0,
        is_checked: {},//单选
        isChooseAll: false, //全选
        is_checkall: false,
        leftChoose: leftChoose,
        value: [this.data.choose, leftChoose],
        page: 1,
        count: 0,
        isopera:false,
        isguige: [],
        load: "加载中..."
      }); 
      one_id = this.data.types[this.data.choose].private_one_class;
      two_id = this.data.leftTypes[leftChoose].private_one_class;
      this.upshoplist();
    };
  }
})